(function ($) {
    function DialogView(element, options) {
        var self = this;
        this.element = element;
        this.options = options;

        this.path = G_Path.path ? G_Path.path : "";
        this.url = options.url ? options.url : this.path + "/goods/cate/level";

        this.fieldId = this.options.id ? this.options.id : "topicId";
        this.fieldName = this.options.id ? this.options.name : "topicName";
        this.dataId = this.options.dataId ? this.options.dataId : "id";
        this.dataName = this.options.dataName ? this.options.dataName : "name";
        this.width = this.options.width;
        this.callback = this.options.callback;
        this.dialog = null;
        this.content = "";
        this.requestData = [];
        this.data = {};
        this.popup = null;
        this.destroyed = false;
        this.keyNum = {KEYBACKSPACE: 8, KEYTAB: 9, KEYENTER: 13, KEYLEFT: 37, KEYUP: 38, KEYRIGHT: 39, KEYDOWN: 40};
        this.curRow = 0;
        this.init();
    }

    DialogView.DEFAULTS = {
        title: "选择品类"
    };
    $.extend(DialogView.prototype, {
        init: function () {
            $(self.element).html("");
            this.popup = $("<div/>").css({
                display: 'none',
                "background-color": "#fff",
                "z-index": 999

            }).appendTo("body");

            this.get();
        },

        get: function () {
            var self = this;
            var url = this.url;
            var requestData = this.options.param ? this.options.param : {};
            $.get(url, requestData, function (text) {
                var data = $.parseJSON(text);
                if (data) {
                    self.requestData = data.list;

                    self.draw(data.list);

                }
                else {

                }

                self.show();
            });
        },
        draw: function (data) {
            var self = this;
            if (this.options.liveSearch) {
                var searchElement = $("<div/>").attr({
                    class: "bs-searchbox"
                }).appendTo(self.popup);

                var div = $("<div class='glyphicon glyphicon-search'></div>").appendTo(searchElement);
                var input = document.createElement('input');
                input.className = 'form-control search-input';
                input.type = "text";
                $(searchElement).append(input);
            }

            var ul = $("<ul class='list-group'></ul>").css({
                "magrin-top": "4px;"
            });
            var className = "list-group-item";
            for (var i = 0; i < data.length; i++) {
                var model = data[i];
                var id = model[this.dataId];
                var name = model[this.dataName];
                if (model.id) {
                    this.addData(id, model);
                    var li = $("<li><a href='javascript:void(0)'></a></li>").attr({
                        "id": id,
                        "class": className
                    }).click(function () {
                        var id = $(this).attr("id");
                        if (self.data && self.data[id]) {
                            var model = self.data[id];
                            var fieldId = self.fieldId;
                            var fieldName = self.fieldName;
                            var id = model[self.dataId];
                            var name = model[self.dataName];
                            $("#" + fieldId).val(id);
                            $("#" + fieldName).val(name);
                            if (self.callback) {
                                self.callback.call(self, model)
                            }
                        }
                        self.close();

                    }).mouseenter(function (event) {
                        this.style.color = "#fff";
                        this.style.backgroundColor = "#337ab7";
                    }).mouseleave(function (event) {
                        this.style.color = "#000";
                        this.style.backgroundColor = "transparent";
                    }).html(name).appendTo(ul);
                }

            }
            $(this.popup).append(ul);
        },
        show: function () {
            var self = this;

            var self = this;
            var dialogOptions = {
                title: this.options.title,
                width: this.width ? this.width : $(self.element).width(),
                quickClose: true,
                content: self.popup

            }
            $(this.popup).show();
            this.dialog = dialog(dialogOptions);
            this.dialog.show($(this.element)[0]);

        },
        /** 关闭浮层 */
        close: function (result) {
            if (this.dialog) {
                this.dialog.close();
            }
            if (!this.destroyed && this.open) {

                if (result !== undefined) {
                    this.returnValue = result;
                }

                this.popup.hide().removeClass(this.className + '-show');
                this.popup.hide();
                this.open = false;
                /*  this.blur();// 恢复焦点，照顾键盘操作的用户
                 this.__dispatchEvent('close');*/
            }

            return this;
        },


        /** 销毁浮层 */
        remove: function () {

            if (this.destroyed) {
                return this;
            }

            this.__dispatchEvent('beforeremove');

            if (Popup.current === this) {
                Popup.current = null;
            }


            // 从 DOM 中移除节点
            this.popup.remove();
            for (var i in this) {
                delete this[i];
            }

            return this;
        },
        // 居中浮层
        _center: function () {

            var popup = this.popup;
            var $window = $(window);
            var $document = $(document);
            var fixed = this.fixed;
            var dl = fixed ? 0 : $document.scrollLeft();
            var dt = fixed ? 0 : $document.scrollTop();
            var ww = $window.width();
            var wh = $window.height();
            var ow = popup.width();
            var oh = popup.height();
            var left = (ww - ow) / 2 + dl;
            var top = (wh - oh) * 382 / 1000 + dt;// 黄金比例
            var style = popup[0].style;
            style.left = Math.max(parseInt(left), dl) + 'px';
            style.top = Math.max(parseInt(top), dt) + 'px';
        },
        _follow: function () {
            var elem = this.element;

            var popup = this.popup;
            if (elem) {
                //如果当前元素是隐藏元素自动居中显示
                var o = $(elem).offset();
                if (o.left * o.top < 0) {
                    return this._center();
                }
            }
            //获取当前元素的宽度和高度
            var width = elem ? elem.outerWidth() : 0;
            var height = elem ? elem.outerHeight() : 0;
            var offset = this._offset(elem);
            var x = offset.left;
            var y = offset.top + height + 2;
            var css = {
                left: x,
                top: y,
                width: width
            };

            $(this.popup).css(css);

        },
        _offset: function (anchor) {

            var isNode = anchor.parentNode;

            var offset = $(anchor).offset();
            return offset;

        },
        addData: function (key, obj) {
            this.data[key] = obj;
        },
        deleteData: function (key) {
            if (this.data && this.data[key]) {
                delete this.data[key];
            }

        },
        toString: function (obj) {
            var rtn = [];
            for (k in obj) {
                if (obj[k] instanceof Object) {
                    for (z in obj[k]) {
                        rtn.push(obj[k][z]);
                    }
                }
                else {
                    rtn.push(obj[k]);
                }

            }
            return rtn.join("");
        }
    });

    $.fn.cate = function (options) {
        var config = $.extend({}, DialogView.DEFAULTS, options);
        var tv = new DialogView(this, config);
    };
})(jQuery);
